import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'custom_model.dart';
import 'flutter_presentation_platform_interface.dart';

/// An implementation of [FlutterPresentationPlatform] that uses method channels.
class MethodChannelFlutterPresentation extends FlutterPresentationPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('flutter_presentation');

  @override
  Future<String?> getPlatformVersion() async {
    final version =
        await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<void> startSubScreen(CustomModel model) async {
    return await methodChannel
        .invokeMethod<void>('startSubScreen', jsonEncode(model).toString());
  }

  @override
  Future<void> startSubScreenWithDisplayId(CustomModel model, int displayId) async {
    final Map<String, dynamic> args = {
      'model': jsonEncode(model).toString(),
      'displayId': displayId
    };
    return await methodChannel.invokeMethod<void>('startSubScreenWithDisplayId', args);
  }
  
  @override
  Future<List<Map<String, dynamic>>> getDisplays() async {
    final String? displayJson = await methodChannel.invokeMethod<String>('getDisplays');
    if (displayJson != null) {
      // The native side returns a JSON String, decode it here.
      final List<dynamic> decodedList = jsonDecode(displayJson);
      // Ensure each item in the list is a Map<String, dynamic>.
      return decodedList.map((item) => Map<String, dynamic>.from(item)).toList();
    } else {
      return [];
    }
  }

  @override
  Future<void> loadData(CustomModel model) async {
    return await methodChannel.invokeMethod("loadData", jsonEncode(model).toString());
  }
}
